package com.iias.communication.util;

import java.util.ArrayList;
import java.util.List;

/**
 * 字节数组操作
 */
public class ByteUtils {

    /**
     * 获取标识符的起始位置
     * @param in
     * @param heardFlag
     * @return
     */
    public static List<Integer> getStartIndex(byte[] in,byte[] heardFlag){
        List<Integer> startIndex = new ArrayList<Integer>();
        for (int i = 0; i < in.length; i++) {
            if (in.length - i < heardFlag.length) {
                continue;
            }
            boolean flag = true;
            for (int j = 0; j < heardFlag.length; j++) {
                if (heardFlag[j] != in[i+j]){
                    flag = false;
                    break;
                };
            }
            if (flag) startIndex.add(i);
        }
        return startIndex;
    }

    /**
     * 数组截取
     * @param src
     * @param begin
     * @param count
     * @return
     */
    public static byte[] subBytes(byte[] src, int begin, int count) {
        byte[] bs = new byte[count];
        System.arraycopy(src, begin, bs, 0, count);
        return bs;
    }


    public static byte[] replace(byte[] in,int start,byte[] oldFlag,byte[] newFlag){
        byte[] startArr = new byte[start-0];
        System.arraycopy(in,0,startArr,0,start);
        byte[] endArr = new byte[in.length-oldFlag.length-start];
        System.arraycopy(in,start+oldFlag.length,endArr,0,endArr.length);

        return  concat(startArr,newFlag,endArr);
    }


    public static byte[] concat(byte[]... arrs) {

        int length = 0;
        for (byte[] arr : arrs) {
            length += arr.length;
        }
        byte[] c= new byte[length];
        int l = 0;
        for (int i = 0; i < arrs.length; i++) {
            System.arraycopy(arrs[i], 0, c, l, arrs[i].length);
            l = l+arrs[i].length;
        }
        return c;

    }
}
